package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.mapper.UserMapperM;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RegexPatterns;
import com.hmdp.utils.RegexUtils;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private UserMapperM userMapperM ;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 发送验证码
     * @param phone 手机号
     * @param session
     * @return
     */
    @Override
    public Result sendCode(String phone, HttpSession session) {
        //校验手机格式是否出错
        if (RegexUtils.isPhoneInvalid(phone)){
            log.debug("手机号格式错误");
            return Result.fail("手机号格式错误");
        }
        //生成随机验证码
        String code = RandomUtil.randomNumbers(6);
        //存放至session
        //session.setAttribute("code",code);

        //存放至redis中，两分钟有效期
        stringRedisTemplate.opsForValue().set((RedisConstants.LOGIN_CODE_KEY + phone),code,RedisConstants.LOGIN_CODE_TTL, TimeUnit.MINUTES);

        log.debug("code为：{}", code);
        return Result.ok(code);
    }


    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //校验手机格式是否出错
        if (RegexUtils.isPhoneInvalid(loginForm.getPhone())){
            log.debug("手机号格式错误");
            return Result.fail("手机号格式错误");
        }

        //从redis中读取code
        String code = stringRedisTemplate.opsForValue().get(RedisConstants.LOGIN_CODE_KEY + loginForm.getPhone());

        //Object code = session.getAttribute("code");

        if (code == null || !code.equals(loginForm.getCode())){
            return Result.fail("验证码错误");
        }

        //根据手机号查询用户
//        User user = query().eq("phone", loginForm.getPhone()).one();
        User user = userMapperM.getByPhone(loginForm.getPhone());

        //判断用户是否存在，不存在则直接创建
        if (user == null ){
            user = createUserByPhone(loginForm.getPhone());
        }

        //uuid
        String token = UUID.randomUUID().toString(true);
        //
        Map<String, Object> stringObjectMap = BeanUtil.beanToMap(user, new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldvalue) -> fieldvalue.toString()));


        //7.保存用户信息到session中
        //session.setAttribute("user", user );

        //保存到redis中
        stringRedisTemplate.opsForHash().putAll((RedisConstants.LOGIN_USER_KEY + token),stringObjectMap);

        String key = RedisConstants.LOGIN_USER_KEY + token;
        stringRedisTemplate.expire(key,RedisConstants.CACHE_SHOP_TTL,TimeUnit.MINUTES);
        return Result.ok(token);
    }

    /**
     * 根据手机号创建用户
     * @param phone
     * @return
     */
    private User createUserByPhone(String phone) {
        User user = new User() ;
        user.setPhone(phone);
        user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        //mybatis-plus
        //save(user);

        //mybatis
        userMapperM.createByPhone(user);

        return user;
    }


}
